﻿Imports WiremetModel.Entities.OEM

Public Class FormaPlatnosciView

    Private _unitOfWork As UnitOfWork
    Private _formaPlatnosciDict As Dictionary(Of Integer, FormaPlatnosci)


    Sub New()
        InitializeComponent()
        _unitOfWork = New UnitOfWork()
        RefreshViewData()
    End Sub

    Private Sub FormaPlatnosciView_Activated(sender As System.Object, e As System.EventArgs) Handles MyBase.Activated
        tb_NazwaPol.SelectAll()
    End Sub

    Private Sub RefreshViewData()

        Dim formaPlatnosciRepository As New Repository(Of FormaPlatnosci)(_unitOfWork)
        _formaPlatnosciDict = formaPlatnosciRepository.GetAll().ToDictionary(Function(x) x.Id, Function(x) x)
        RefreshFormaPlatnosciTable(_formaPlatnosciDict.Values.OrderBy(Function(x) x.NazwaPol))

    End Sub

    Private Sub RefreshFormaPlatnosciTable(ByVal formaPlatnosciList As IEnumerable(Of FormaPlatnosci))

        dgv_FormyPlatnosci.Rows.Clear()

        For Each formaPlatnosci As FormaPlatnosci In formaPlatnosciList
            dgv_FormyPlatnosci.Rows.Add(
                formaPlatnosci.Id,
                formaPlatnosci.NazwaPol,
                formaPlatnosci.NazwaAng,
                formaPlatnosci.LiczbaDni)
        Next
    End Sub

    Private Sub UpdateValues(ByVal formaPlatnosci As FormaPlatnosci)

        tb_NazwaPol.Text = formaPlatnosci.NazwaPol
        tb_NazwaAng.Text = formaPlatnosci.NazwaAng
        tb_LiczbaDni.Text = formaPlatnosci.LiczbaDni.ToString()

    End Sub

    Private Sub dgv_FormyPlatnosci_SelectionChanged(sender As System.Object, e As EventArgs) Handles dgv_FormyPlatnosci.SelectionChanged
        If dgv_FormyPlatnosci.SelectedRows.Count > 0 Then
            Dim id As Integer = CInt(dgv_FormyPlatnosci.SelectedRows(0).Cells("Id").Value)
            UpdateValues(_formaPlatnosciDict(id))
            tb_NazwaPol.SelectAll()
        End If
    End Sub

    Private Function IsTextInputValid(ByVal textBox As TextBox) As Boolean
        Return Not String.IsNullOrEmpty(textBox.Text.Trim())
    End Function

    Private Function IsLiczbaDniInputValid() As Boolean

        Dim intVal As Integer = 0
        Integer.TryParse(tb_LiczbaDni.Text, intVal)
        Return intVal > 0 OrElse String.IsNullOrEmpty(tb_LiczbaDni.Text)

    End Function

    Private Function AreValuesValid() As Boolean

        Return IsTextInputValid(tb_NazwaPol) AndAlso
               IsTextInputValid(tb_NazwaAng) AndAlso
               IsLiczbaDniInputValid()

    End Function

    Private Function IsFormaPlatnosciUnique(ByVal candidate As FormaPlatnosci) As Boolean

        For Each formaPlatnosci In _formaPlatnosciDict.Values
            If candidate.NazwaPol = formaPlatnosci.NazwaPol AndAlso
               candidate.NazwaAng = formaPlatnosci.NazwaAng AndAlso
               candidate.LiczbaDni = formaPlatnosci.LiczbaDni Then
                Return False
            End If
        Next
        Return True

    End Function

    Private Sub btn_Add_Click(sender As System.Object, e As System.EventArgs) Handles btn_Add.Click

        Try
            If Not AreValuesValid() Then
                Throw New EntityDataInputException("Wprowadzone wartości są niepoprawne.")
            End If

            Dim formaPlatnosci As New FormaPlatnosci()
            With formaPlatnosci
                .NazwaPol = tb_NazwaPol.Text.Trim()
                .NazwaAng = tb_NazwaAng.Text.Trim()
                ' wtf ternary cant assign nothing
                If tb_LiczbaDni.Text.Trim() = String.Empty Then
                    .LiczbaDni = Nothing
                Else
                    .LiczbaDni = Integer.Parse(tb_LiczbaDni.Text.Trim())
                End If
            End With

            If Not IsFormaPlatnosciUnique(formaPlatnosci) Then
                Throw New EntityDataInputException("Wprowadzone wartości są niepoprawne." & vbCrLf &
                                                            "Podana forma płatności już istnieje.")
            End If

            _unitOfWork.BeginTransaction()
            Dim formaPlatnosciRepository As New Repository(Of FormaPlatnosci)(_unitOfWork)
            formaPlatnosciRepository.Add(formaPlatnosci)
            _unitOfWork.CommitTransaction()

            _formaPlatnosciDict.Add(formaPlatnosci.Id, formaPlatnosci)
            dgv_FormyPlatnosci.Rows.Add(formaPlatnosci.Id, formaPlatnosci.NazwaPol, formaPlatnosci.NazwaAng, formaPlatnosci.LiczbaDni)
            dgv_FormyPlatnosci.Sort(dgv_FormyPlatnosci.Columns("NazwaPol"), System.ComponentModel.ListSortDirection.Ascending)

        Catch ex As EntityDataInputException
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            tb_NazwaPol.SelectAll()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            _unitOfWork.Dispose()
            _unitOfWork = New UnitOfWork()
        End Try
    End Sub

    Private Sub btn_Edit_Click(sender As System.Object, e As System.EventArgs) Handles btn_Edit.Click

        Try
            If dgv_FormyPlatnosci.SelectedRows.Count = 0 Then
                Throw New Exception("Proszę wybierz formę płatności, którą chciałbyś zmienić.")
            End If

            If Not AreValuesValid() Then
                Throw New EntityDataInputException("Wprowadzone wartości są niepoprawne.")
            End If

            If Not IsFormaPlatnosciUnique(New FormaPlatnosci With
                                          {.LiczbaDni = Integer.Parse(tb_LiczbaDni.Text.Trim()),
                                           .NazwaPol = tb_NazwaPol.Text.Trim(),
                                           .NazwaAng = tb_NazwaAng.Text.Trim()}) Then
                Throw New EntityDataInputException("Wprowadzone wartości są niepoprawne.\n" & vbCrLf &
                                                            "Podana forma płatności już istnieje.")
            End If

            Dim id As Integer = CInt(dgv_FormyPlatnosci.SelectedRows(0).Cells("Id").Value)
            Dim rowIndex As Integer = dgv_FormyPlatnosci.SelectedRows(0).Index
            Dim formaPlatnosci As FormaPlatnosci = _formaPlatnosciDict(id)

            With formaPlatnosci
                .NazwaPol = tb_NazwaPol.Text.Trim()
                .NazwaAng = tb_NazwaAng.Text.Trim()
                If tb_LiczbaDni.Text.Trim() = String.Empty Then
                    .LiczbaDni = Nothing
                Else
                    .LiczbaDni = Integer.Parse(tb_LiczbaDni.Text.Trim())
                End If
            End With

            _unitOfWork.BeginTransaction()
            Dim formaPlatnosciRepository As New Repository(Of FormaPlatnosci)(_unitOfWork)
            formaPlatnosciRepository.Update(formaPlatnosci)
            _unitOfWork.CommitTransaction()

            ' sprawdzic czy zmienilo sie w dict
            dgv_FormyPlatnosci.Rows(rowIndex).SetValues(formaPlatnosci.Id, formaPlatnosci.NazwaPol, formaPlatnosci.NazwaAng, formaPlatnosci.LiczbaDni)
            dgv_FormyPlatnosci.Sort(dgv_FormyPlatnosci.Columns("NazwaPol"), System.ComponentModel.ListSortDirection.Ascending)

        Catch ex As EntityDataInputException
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
            tb_NazwaPol.SelectAll()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            _unitOfWork.Dispose()
            _unitOfWork = New UnitOfWork()
        End Try

    End Sub

    Private Sub btn_Delete_Click(sender As System.Object, e As System.EventArgs) Handles btn_Delete.Click

        Try
            If dgv_FormyPlatnosci.SelectedRows.Count = 0 Then
                Throw New Exception("Proszę wybierz formę płatności, którą chciałbyś usunąć.")
            End If

            Dim confirmationResult As DialogResult = MessageBox.Show("Czy na pewno chcesz usunąć wskazaną formę płatności?", "Uwaga", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
            If confirmationResult = Windows.Forms.DialogResult.Yes Then

                Dim id As Integer = CInt(dgv_FormyPlatnosci.SelectedRows(0).Cells("Id").Value)
                Dim rowIndex As Integer = dgv_FormyPlatnosci.SelectedRows(0).Index
                Dim formaPlatnosci As FormaPlatnosci = _formaPlatnosciDict(id)

                ' check foreign key constraints
                _unitOfWork.BeginTransaction()
                Dim formaPlatnosciRepository As New Repository(Of FormaPlatnosci)(_unitOfWork)
                formaPlatnosciRepository.Delete(formaPlatnosci)
                _unitOfWork.CommitTransaction()

                _formaPlatnosciDict.Remove(id)
                dgv_FormyPlatnosci.Rows.RemoveAt(rowIndex)

            End If

        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            _unitOfWork.Dispose()
            _unitOfWork = New UnitOfWork()
        End Try

    End Sub

    
End Class